package io.renren.modules.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.exception.RRException;
import io.renren.common.utils.MailUtil;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.generator.dto.MemberDTO;
import io.renren.modules.generator.entity.TEventEntity;
import io.renren.modules.generator.entity.TMemberEntity;
import io.renren.modules.generator.service.TEventService;
import io.renren.modules.generator.service.TMemberService;
import io.renren.modules.yunxin.YunxinUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.*;

@RestController
@RequestMapping("/app")
@Api("APP登录接口")
public class AppApiController {
    @Autowired
    private TMemberService memberService;
    @Autowired
    private TEventService eventService;
    /**
     * 登录
     */
    @RequestMapping("sendEmail")
    @ApiOperation("sendEmail")
    public R sendEmail(@RequestParam("email") String email, HttpServletRequest request) throws MessagingException, UnsupportedEncodingException {
        if (email.length()==0) {
            throw new RRException("length not zero");
        }
        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
        //将验证码存到session中,同时存入创建时间
        //以json存放，这里使用的是阿里的fastjson
        HttpSession session = request.getSession();
        JSONObject json = null;
        MailUtil.sendMail(email,verifyCode);
        json = new JSONObject();
        json.put("email", email);
        json.put("verifyCode", verifyCode);
        json.put("createTime", System.currentTimeMillis());
        // 将认证码存入SESSION
        request.getSession().setAttribute("verifyCode", json);
        return R.ok();
    }


    /**
     * 获取家族阵列数据
     */
    @Login
    @RequestMapping("getFamilyTree")
    @ApiOperation("getFamilyTree")
    public R getFamilyTree(@RequestAttribute("userId") Integer userId) {
        List<List<MemberDTO>> twoDimensional = new ArrayList<>();

//        获取当前用户子女
        TMemberEntity centerMember=memberService.getById(userId);

        List<TMemberEntity> childList= memberService.list(new QueryWrapper<TMemberEntity>().eq("fatherid",userId).or().eq("motherid",userId));
        if (centerMember.getSpouseid()!=null){
            List<TMemberEntity> spouseList= memberService.list(new QueryWrapper<TMemberEntity>().eq("fatherid",centerMember.getSpouseid()).or().eq("motherid",centerMember.getSpouseid()));
            childList.addAll(spouseList);
        }
        List<MemberDTO> newList=new ArrayList<>();
        Set<Integer> userIdSet = new HashSet<>();
        for (int j = 0; j <childList.size() ; j++) {
            TMemberEntity memberEntity= childList.get(j);
            if (userIdSet.contains(memberEntity.getUserid())){
                break;
            }
            MemberDTO memberDTO= new MemberDTO();
//            如果没有配偶
            if (memberEntity.getSpouseid()==null||memberEntity.getSpouseid()==0){
                if (memberEntity.getGender()==0){
                    memberDTO.setFather(memberEntity);
                }else{
                    memberDTO.setMother(memberEntity);
                }
                memberDTO.setIsCouple(0);
                userIdSet.add(memberEntity.getUserid());

            }else{
                TMemberEntity spouse=memberService.getById(memberEntity.getSpouseid());
                if (memberEntity.getGender()==0){
                    memberDTO.setFather(memberEntity);
                    memberDTO.setMother(spouse);
                }else{
                    memberDTO.setMother(memberEntity);
                    memberDTO.setFather(spouse);
                }
                memberDTO.setIsCouple(1);
                userIdSet.add(memberEntity.getUserid());
                userIdSet.add(spouse.getUserid());

            }

            newList.add(memberDTO);

        }


        twoDimensional.add(newList);

//        中心点
        List<MemberDTO> centerList=new ArrayList<>();
//        TMemberEntity father = memberService.getById(centerMember.getFatherid());
//        TMemberEntity mother = memberService.getById(centerMember.getMotherid());

        MemberDTO centerMemberDTO=new MemberDTO();
        if (centerMember.getGender()==0) {
            centerMemberDTO.setFather(centerMember);
            if (centerMember.getSpouseid()!=null){
                TMemberEntity spouse = memberService.getById(centerMember.getSpouseid());
                centerMemberDTO.setMother(spouse);
                centerMemberDTO.setIsCouple(1);
            }else{
                centerMemberDTO.setIsCouple(0);
            }
        }else{
            centerMemberDTO.setMother(centerMember);
            if (centerMember.getSpouseid()!=null){
                TMemberEntity spouse = memberService.getById(centerMember.getSpouseid());
                centerMemberDTO.setFather(spouse);
                centerMemberDTO.setIsCouple(1);
            }else{
                centerMemberDTO.setIsCouple(0);
            }
        }

        centerList.add(centerMemberDTO);
        twoDimensional.add(centerList);

//        递归找父层
        List<MemberDTO> tempList= new ArrayList<>();
        this.getParentListBy(centerList,twoDimensional);


        Collections.reverse(twoDimensional);
        return R.ok().put("list",twoDimensional);
    }

    void getParentListBy(List<MemberDTO> list,List<List<MemberDTO>> globalList){
        List<MemberDTO> newList=new ArrayList<>();

        for (int i = 0; i <list.size() ; i++) {
            MemberDTO temp =list.get(i);

//            父亲不为空，找爷爷奶奶
            if (temp.getFather()!=null){
                MemberDTO memberDTO=new MemberDTO();
                if (temp.getFather().getFatherid()!=null){
                    TMemberEntity father=memberService.getById(temp.getFather().getFatherid());
                    memberDTO.setFather(father);
                }
                if (temp.getFather().getMotherid()!=null){
                    TMemberEntity mother=memberService.getById(temp.getFather().getMotherid());
                    memberDTO.setMother(mother);
                }
                if (memberDTO.getFather()!=null&&memberDTO.getMother()!=null){
                    memberDTO.setIsCouple(1);
                }
                if (memberDTO.getFather()!=null||memberDTO.getMother()!=null){
                    newList.add(memberDTO);
                }

            }
//            母亲不为空，找外婆，外公
            if (temp.getMother()!=null){
                MemberDTO memberDTO=new MemberDTO();
                if (temp.getMother().getFatherid()!=null){
                    TMemberEntity father=memberService.getById(temp.getMother().getFatherid());
                    memberDTO.setFather(father);
                }
                if (temp.getMother().getMotherid()!=null){
                    TMemberEntity mother=memberService.getById(temp.getMother().getMotherid());
                    memberDTO.setMother(mother);
                }
                if (memberDTO.getFather()!=null&&memberDTO.getMother()!=null){
                    memberDTO.setIsCouple(1);
                }
                if (memberDTO.getFather()!=null||memberDTO.getMother()!=null){
                    newList.add(memberDTO);
                }

            }
        }
        if (newList.size()!=0) {
            globalList.add(newList);
            this.getParentListBy(newList,globalList);
        }


    }


    /**
     * 用户信息
     */
    @Login
    @RequestMapping("getUserInfo")
    @ApiOperation("getUserInfo")
    public R getUserInfo(@RequestParam("user_id") Integer userId) {
        TMemberEntity memberEntity=memberService.getById(userId);
        return R.ok().put("data",memberEntity);
    }

    /**
     * 配偶信息
     */
    @Login
    @RequestMapping("getSpouseInfo")
    @ApiOperation("getSpouseInfo")
    public R getSpouseInfo(@RequestParam("user_id") Integer userId) {
        TMemberEntity memberEntity=memberService.getById(userId);
        if (memberEntity.getSpouseid()==null){
            return R.ok("没有配偶");
        }
        TMemberEntity spouseMember=memberService.getById(memberEntity.getSpouseid());

        return R.ok().put("data",spouseMember);
    }


    /**
     * 子女信息
     */
    @Login
    @RequestMapping("getChildList")
    @ApiOperation("getChildList")
    public R getChildList(@RequestParam("user_id") Integer userId) {
        TMemberEntity memberEntity=memberService.getById(userId);

        List<TMemberEntity> myList= memberService.list(new QueryWrapper<TMemberEntity>().eq("fatherid",userId).or().eq("motherid",userId));
        if (memberEntity.getSpouseid()!=null){
            List<TMemberEntity> spouseList= memberService.list(new QueryWrapper<TMemberEntity>().eq("fatherid",memberEntity.getSpouseid()).or().eq("motherid",memberEntity.getSpouseid()));
            myList.addAll(spouseList);
        }
        List<TMemberEntity> newList=new ArrayList<>();
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < myList.size(); i++) {
            TMemberEntity temp=myList.get(i);
            if (set.contains(temp.getUserid())){
                break;
            }else{
                newList.add(temp);
                set.add(temp.getUserid());
            }
        }

        return R.ok().put("list",newList);
    }


    /**
     * 父母信息
     */
    @Login
    @RequestMapping("getParents")
    @ApiOperation("getParents")
    public R getParents(@RequestParam("user_id") Integer userId) {
        TMemberEntity memberEntity=memberService.getById(userId);

        Map<String,Object> map =new HashMap<>();
        if (memberEntity.getFatherid()!=null){
            TMemberEntity father=memberService.getById(memberEntity.getFatherid());
            map.put("father",father);

        }
        if (memberEntity.getMotherid()!=null){
            TMemberEntity mother=memberService.getById(memberEntity.getMotherid());
            map.put("mother",mother);

        }


        return R.ok().put("data",map);
    }

    @Login
    @RequestMapping("getyunxinAccount")
    @ApiOperation("getyunxinAccount")
    public R getyunxinAccount(@RequestAttribute("userId") Integer userId) throws Exception{
        TMemberEntity member=memberService.getById(userId);
        if(member.getYunxinid()==null){
            String yunxinAccount = StringUtils.getUUID();
            boolean ret=YunxinUtils.register(yunxinAccount);
            if (ret){
                member.setYunxinid(yunxinAccount);
                memberService.updateById(member);
            }

        }



        return R.ok().put("yunxinId",member.getYunxinid());
    }


    @Login
    @RequestMapping("getyunxinUserList")
    @ApiOperation("getyunxinUserList")
    public R getyunxinUserList(@RequestAttribute("userId") Integer userId) throws Exception{
        TMemberEntity member=memberService.getById(userId);
        List<TMemberEntity> list = memberService.list(new QueryWrapper<TMemberEntity>().isNotNull("yunxinid").eq(false,"yunxinid",member.getYunxinid()));

        return R.ok().put("list",list);
    }
    /**
     * 父母信息
     */
    @Login
    @RequestMapping("addFamilyMember")
    @ApiOperation("addFamilyMember")
    public R addFamilyMember(@RequestAttribute("userId") Integer userId,@RequestParam("memberId") Integer memberId,@RequestParam("name") String name,@RequestParam("gender") Integer gender,@RequestParam("level") Integer level,@RequestParam("role") Integer role) {

     //role 1 配偶，2，儿女，3父母
        TMemberEntity memberEntity= new TMemberEntity();
        memberEntity.setCreatetime(new Date());
        memberEntity.setName(name);
        memberEntity.setGender(gender);

        memberEntity.setModifytime(new Date());
        memberEntity.setLevel(level);
        memberEntity.setFamilyid(memberId);
        if (role==1){
//             配偶
            memberEntity.setSpouseid(memberId);

        }else if (role==2){
//            子女
            TMemberEntity spouse=memberService.getById(memberId);
            if (spouse.getGender()==0){
                memberEntity.setFatherid(memberId);
            }else{
                memberEntity.setMotherid(memberId);
            }
        }else {
            TMemberEntity temp=memberService.getById(memberId);
            if (temp.getFatherid()!=null){
                if (gender==0){
                    return R.error("hava a father");
                }
            }
            if (temp.getMotherid()!=null){
                if (gender==1){
                    return R.error("hava a mother");
                }
            }
        }
        memberService.save(memberEntity);
        if (role==1){

            TMemberEntity spouse=memberService.getById(memberId);
            spouse.setSpouseid(memberEntity.getUserid());
            memberService.updateById(spouse);

        }else if (role==3){
            TMemberEntity spouse=memberService.getById(memberId);
            if (gender==0){
                spouse.setFatherid(memberEntity.getUserid());
                if (spouse.getMotherid()!=null){
                    TMemberEntity father=memberService.getById(spouse.getFatherid());
                    TMemberEntity mother=memberService.getById(spouse.getMotherid());
                    father.setSpouseid(spouse.getMotherid());
                    mother.setSpouseid(spouse.getFatherid());
                    memberService.updateById(father);
                    memberService.updateById(mother);
                }
            }else{
                spouse.setMotherid(memberEntity.getUserid());
                if (spouse.getFatherid()!=null){
                    TMemberEntity father=memberService.getById(spouse.getFatherid());
                    TMemberEntity mother=memberService.getById(spouse.getMotherid());
                    father.setSpouseid(spouse.getMotherid());
                    mother.setSpouseid(spouse.getFatherid());
                    memberService.updateById(father);
                    memberService.updateById(mother);
                }
            }
            memberService.updateById(spouse);
        }

        return R.ok();
    }


    @Login
    @RequestMapping("getEventList")
    @ApiOperation("getEventList")
    public R getEventList(@RequestAttribute("userId") Integer userId) throws Exception{

        List<TEventEntity> list = eventService.list();

        return R.ok().put("list",list);
    }
//    @Login
    @RequestMapping("eventSave")
    @ApiOperation("eventSave")
    public R eventSave(@RequestBody TEventEntity tEvent){
        if (tEvent.getId()==null){
//            tEvent.setCreateid(0);
            eventService.save(tEvent);
        }else{
            if (tEvent.getContent().length()==0){
                eventService.removeById(tEvent.getId());
            }else{
                tEvent.setModifytime(new Date());
                eventService.updateById(tEvent);
            }
        }


        return R.ok();
    }
}
